package com.hua.fanqiemall.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.hua.fanqiemall.product.constant.ProductConstant;
import com.hua.fanqiemall.product.dao.AttrAttrgroupRelationDao;
import com.hua.fanqiemall.product.dao.AttrGroupDao;
import com.hua.fanqiemall.product.dao.CategoryDao;
import com.hua.fanqiemall.product.entity.AttrAttrgroupRelationEntity;
import com.hua.fanqiemall.product.entity.AttrGroupEntity;
import com.hua.fanqiemall.product.entity.CategoryEntity;
import com.hua.fanqiemall.product.service.CategoryService;
import com.hua.fanqiemall.product.vo.AttrGroupRelationReqVo;
import com.hua.fanqiemall.product.vo.AttrRspVo;
import com.hua.fanqiemall.product.vo.AttrReqVo;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hua.common.utils.PageUtils;
import com.hua.common.utils.Query;

import com.hua.fanqiemall.product.dao.AttrDao;
import com.hua.fanqiemall.product.entity.AttrEntity;
import com.hua.fanqiemall.product.service.AttrService;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao relationDao;
    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private CategoryService categoryService;

    private static final Logger logger = LoggerFactory.getLogger(AttrServiceImpl.class);
    /**
     * 原始分页查询
     * @param params 查询参数
     * @return PageUtils
     */
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<>()
        );
        return new PageUtils(page);
    }

    /**
     * 保存商品属性
     * @author luoweihua
     * @date 2022/1/11 10:10
     * @param attrReqVo 商品属性
     */
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public void saveAttr(AttrReqVo attrReqVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrReqVo,attrEntity);
        //保存基本数据
        this.save(attrEntity);
        //保存关联关系
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attrReqVo.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attrReqVo.getAttrGroupId());
            relationDao.insert(attrAttrgroupRelationEntity);
        }
    }

    /**
     * 查询商品属性以及销售属性
     * @param params 查询参数
     * @param catelogId 分类ID
     * @param attrType 属性类型：base-基本属性，sale-销售属性
     * @return PageUtils
     */
    @Override
    public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
        logger.info("查询商品属性以及销售属性接口：入参：{},分类id：{},查询类型：{}",params,catelogId,attrType);
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("attr_type","base".equals(attrType) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if (catelogId != 0){
            queryWrapper.eq("catelog_id",catelogId);
        }
        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)){
            queryWrapper.and((wrapper)-> wrapper.eq("attr_id",key).or().like("attr_name",key));
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params),queryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();

        List<AttrRspVo> rspVoList = new ArrayList<>();
        for (AttrEntity record : records) {
            AttrRspVo attrRspVo = new AttrRspVo();
            BeanUtils.copyProperties(record,attrRspVo);
            //设置分类和分组信息
            if ("base".equals(attrType)) {
                AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", record.getAttrId()));
                if (relationEntity != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                    if (attrGroupEntity != null) {
                        attrRspVo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }
            CategoryEntity categoryEntity = categoryDao.selectById(record.getCatelogId());
            if (categoryEntity != null) {
                attrRspVo.setCatelogName(categoryEntity.getName());
            }
            rspVoList.add(attrRspVo);
        }
        pageUtils.setList(rspVoList);
        logger.info("查询商品属性以及销售属性出参：{}", JSONObject.toJSONString(pageUtils));
        return pageUtils;
    }

    /**
     * 获取商品属性信息
     * @author luoweihua
     * @date 2022/1/11 13:58
     * @param attrId 商品属性id
     * @return AttrRspVo
     */
    @Override
    public AttrRspVo getAttrInfo(Long attrId) {
        AttrRspVo attrRspVo = new AttrRspVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,attrRspVo);

        //1、设置分组信息
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationEntity != null) {
                attrRspVo.setAttrGroupId(relationEntity.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
                if (attrGroupEntity != null) {
                    attrRspVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }

        //2、设置分类信息
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.findCatelogPath(catelogId);
        attrRspVo.setCatelogPath(catelogPath);
        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null){
            attrRspVo.setCatelogName(categoryEntity.getName());
        }
        return attrRspVo;
    }
    /**
     * 更新商品属性信息
     * @author luoweihua
     * @date 2022/1/11 13:58
     * @param attrReqVo 属性
     */
    @Override
    public void updateAttr(AttrReqVo attrReqVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrReqVo,attrEntity);
        this.updateById(attrEntity);

        //修改属性分组关联
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrReqVo.getAttrId());
            relationEntity.setAttrGroupId(attrReqVo.getAttrGroupId());
            Long count = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrReqVo.getAttrId()));
            if (count > 0) {
                relationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrReqVo.getAttrId()));
            } else {
                relationDao.insert(relationEntity);
            }
        }
    }

    /**
     * 根据分组id找到所有关联的属性
     * @author luoweihua
     * @date 2022/1/11 16:16
     * @param attrGroupId 分组id
     * @return List<AttrEntity>
     */
    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        List<AttrEntity> result = new ArrayList<>();
        List<Long> attrIdList = new ArrayList<>();

        List<AttrAttrgroupRelationEntity> relationList = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        for (AttrAttrgroupRelationEntity relationEntity : relationList) {
            attrIdList.add(relationEntity.getAttrId());
        }
        if (attrIdList.size()>0){
            result = this.listByIds(attrIdList);
        }
        return result;
    }

    /**
     * 获取属性分组没有关联的其他属性
     * @author luoweihua
     * @date 2022/1/11 18:15
     * @param params 查询参数
     * @param attrGroupId 属性分组id
     * @return PageUtils
     */
    @Override
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrGroupId) {
        //1、当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2、当前分组只能关联别的分组没有引用的属性
        //2.1)当前分类下的其他分组
        List<AttrGroupEntity> groupEntityList = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        //2.2)这些分组关联的属性
        List<Long> groupIdList = new ArrayList<>();
        for (AttrGroupEntity groupEntity : groupEntityList) {
            groupIdList.add(groupEntity.getAttrGroupId());
        }
        List<AttrAttrgroupRelationEntity> relationEntityList = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIdList));
        //2.3)从当前分类的所有属性中移除这些属性
        List<Long> attrIdList = new ArrayList<>();
        for (AttrAttrgroupRelationEntity relationEntity : relationEntityList) {
            attrIdList.add(relationEntity.getAttrId());
        }
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        if (attrIdList.size()>0){
            queryWrapper.notIn("attr_id", attrIdList);
        }

        String key = (String) params.get("key");
        if (StringUtils.isNotBlank(key)){
            queryWrapper.and((wrapper)-> wrapper.eq("attr_id",key).or().like("attr_name",key));
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        return new PageUtils(page);
    }

    /**
     * 批量删除属性与分组的关联关系
     * @author luoweihua
     * @date 2022/1/11 16:39
     * @param reqVoListVo 删除列表
     */
    @Override
    public void deleteRelation(List<AttrGroupRelationReqVo> reqVoListVo) {
        List<AttrAttrgroupRelationEntity> relationEntityList = new ArrayList<>();
        for (AttrGroupRelationReqVo reqVo : reqVoListVo) {
            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(reqVo,entity);
            relationEntityList.add(entity);
        }
        relationDao.deleteBatchRelation(relationEntityList);
    }
}